<?php
/**
 * 店铺控制器 (分销)
 * @version 2015080610
 * @author Max.Yu <max@jipu.com>
 */

namespace Home\Controller;

class ShopsController extends HomeController{

  protected function _initialize(){
    //记录当前页URL地址Cookie，点击我的登录完成后跳转至个人中心
    Cookie('__forward__', $_SERVER['REQUEST_URI']);
    parent::_initialize();
    //跳过验证登录
    $jump_loginlist = array('detail');
    if(!in_array(ACTION_NAME, $jump_loginlist)){
      parent::login();
    }
    $this->assign('user', $this->user);
    $this->assign('member', $this->member);
  }

  /**
   * 店铺详情
   * @author Max.Yu <max@jipu.com>
   */
  public function detail($uid = 0){
    $data = M('Shop')->where(array('uid' => $uid, 'status' => 1))->find();
    if($data){
        $item_category_model = D('ItemCategory');
        $cid = I('get.cid');
        //获取商品分类（关于本店的）
        //获取当前类所在层级
        if(empty($cid)) {
            $cid=0;
            $cates[] = array('item' => D('Shop')->getChild($cid, $data['item_ids']), 'pid' => $cid, 'cid' => 0);
        }else{
            $where['cid_1|cid_2|cid_3'] = $cid;
            $cates[] = array('item' => D('Shop')->getChild($cid), 'pid' => $cid, 'cid' => 0);
        }

        $cate_active[$cid][0] = 'current';

        if(count($cates[0]['item'])==0)$cates=array();
        $pid=$cid;
        while($pid>0){
            //var_dump($pid);
            //查看是否是顶级分类
            $status = M('ItemCategory')->where("id='{$pid}'")->getField('pid');
            //var_dump($status);
            if($status == 0){
                $item_tmp = D('Shop')->getChild('',$data['item_ids']);
            }else{
                $item_tmp=$item_category_model->getBrother($pid);
            }
            $item_info=$item_category_model->info($pid);
            $cate_active[$item_tmp[0]['pid']][$pid] = 'current';
            $cates[]=array('item'=>$item_tmp,'cid'=>$pid,'cname'=>$item_info['name'],'pid'=>$item_tmp[0]['pid']);
            $pid=$item_tmp[0]['pid'];
        }
        //var_dump($cate_active);
        $cates=array_reverse($cates);
        //设置当前排序条件的活动样式
        $order_css['active'][I('get._field')][I('get._order')] = 'active';
      //记录分销店铺sdp_uid到SESSION
      session('sdp_uid', $data['uid']);
      //商品列表
        $where['status'] = 1;
        $where['id'] = array('IN', $data['item_ids']);
        $where['sdp'] = array('gt', 0);

      $order = "INSTR('{$data['item_ids']}', id)";
        if(C('START_POSITION') && session('zone.id')){
            $city = session('zone.district') ? session('zone.district') : session('zone.id');
            $where['_string'] = 'FIND_IN_SET("'.$city.'" , set_zone)';
        }
      $lists = $this->lists('Item', $where, $order, '*', 40);
      foreach($lists as &$value){
        if($value['thumb']){
          $value['cover_path'] = get_cover($value['thumb'], 'path');
        }
      }
        $this->category = $cates;
        $this->uid = $uid;
        $this->cid = $cid;
        $this->cate_active = $cate_active;
        $this->order_css = $order_css;
      $this->lists = $lists;
      $this->data = $data;
      $this->meta_title = $data['name'] ? $data['name'] : '无名店铺';
      $share = array(
        'title' => $this->meta_title,
        'desc' => $data['intro'] ? $data['intro'] : C('WEB_SITE_DESCRIPTION'),
        'img_url' => $data['logo'] ? SITE_URL.$data['logo'] : null,
        'link' => SITE_URL.U('Shops/detail', array('uid' => $uid))
      );
      $this->meta_share = $share;
    }else{
      $this->error('不存在的店铺！');
    } 
    $this->display(IS_AJAX ? 'Item/itemList' : null);
  }

  /**
   * 店铺管理
   * @author Max.Yu <max@jipu.com>
   */
  public function manage(){
    if(IS_POST){
      $res = D('Shop')->update();
      if($res){
        $this->success('店铺信息设置成功！',U('Shops/item'));
      }else{
        $this->error(D('Shop')->getError());
      }
    }else{
      $data = M('Shop')->getByUid(UID);
      if($data['status'] != 1){
        $this->redirect('Shops/add');
      }
      $this->data = $data;
    }
    $this->meta_title = '店铺设置';
    $this->display();
  }

  /**
   * 商品管理
   * @author Max.Yu <max@jipu.com>
   */
  public function item(){
    $shop_data = M('Shop')->where(array('uid' => UID, 'status' => 1))->find();
    $where = array(
      'id' => array('IN', $shop_data['item_ids']),
      'status' => 1,
    );
    if($shop_data['item_ids'])$lists = $this->lists('Item', $where, 'id desc', 'id, name, price, images, thumb, sdp_type, sdp', 24);
    $lists = A('Item', 'Event')->formatList($lists);
    if($shop_data){
      $shop_data['items'] = explode(',', $shop_data['item_ids']);
    }

    $this->shop_data = $shop_data;
    $this->lists = $lists;
    $this->meta_title = '商品管理';
    $this->display(IS_AJAX ? 'itemList' : null);
  }

  /**
   * 选择商品
   * @author Max.Yu <max@jipu.com>
   */
  public function selectItem($status = null, $keywords = null, $cid_1 = null, $cid_2 = null, $cid_3 = null, $stock = null,$storeName = null){
    //商品分类
      $this->cid_1 = D('itemCategory')->getTree(0,'id,pid,name');
       // dump($cid_1);
      if($cid_1){
          $where['cid_1'] = $cid_1;
          $this->cid_2 = D('itemCategory')->getTree($cid_1,'id,pid,name');
      }
      if($cid_2){
          $where['cid_2'] = $cid_2;
          $this->cid_3 = D('itemCategory')->getTree($cid_2,'id,pid,name');
      }
      if($cid_3){
          $where['cid_3'] = $cid_3;
      }




      $shop_data = M('Shop')->where(array('uid' => UID, 'status' => 1))->find();
    $where = array(
      'status' => 1,
      'sdp' => array('gt', 0)
    );
    $lists = $this->lists('Item', $where, 'id desc', 'id, name, price, images, thumb, sdp_type, sdp', 24);
 
      $lists = A('Item', 'Event')->formatList($lists);

      if($lists){
          foreach($lists as &$v){

              //分类处理
              if($v['cid_1']){
                  $v['category'] = M('item_category')->where(array('id'=>$v['cid_1']))->getField('name');
              }
              if($v['cid_2']){
                  $v['category'] .= '/'. M('item_category')->where(array('id'=>$v['cid_2']))->getField('name');
              }
              if($v['cid_3']){
                  $v['category'] .= '/'. M('item_category')->where(array('id'=>$v['cid_3']))->getField('name');
              }
          }
      }

    if($shop_data){
      $shop_data['items'] = explode(',', $shop_data['item_ids']);
    }
    $this->shop_data = $shop_data;
    $this->lists = $lists;
    $this->meta_title = '选择商品';
    $this->display(IS_AJAX ? 'itemList' : null);
  }

  /**
   * 添加商品到店铺
   * @author Max.Yu <max@jipu.com>
   */
  public function addItem(){
    $itemid = I('post.itemid', 0);
    if(empty($itemid)){
      $this->error('非法请求！');
    }
    $shop_model = D('Shop');
    $res = $shop_model->addItem($itemid);
    if($res){
      $this->success('成功添加到您的店铺！');
    }else{
      $this->error($shop_model->getError());
    }
  }

  /**
   * 删除店铺商品
   * @author Max.Yu <max@jipu.com>
   */
  public function removeItem(){
    $itemid = I('post.itemid', 0);
    if(empty($itemid)){
      $this->error('非法请求！');
    }
    $shop_model = D('Shop');
    $res = $shop_model->removeItem($itemid);
    if($res){
      $this->success('删除成功！');
    }else{
      $this->error($shop_model->getError());
    }
  }

  /**
   * 订单管理
   * @author Max.Yu <max@jipu.com>
   */
  public function order($uid = 0){
      $prefix= C('DB_PREFIX');
      //$model = M()->table($prefix."order_item a")->join($prefix."order b on b.id= a.order_id")->join($prefix."shop c on c.secret=a.sdp_code")->join($prefix."finance d on b.id=d.order_id");
      $model = M()->table($prefix."order a")->join($prefix."finance b on a.id=b.order_id");
      $where  = array(
          //'c.uid'       => UID ,
          //$condition['_string'] = "FIND_IN_SET(a.item_id,b.item_ids)",
          'b.uid'       => UID ,
          'a.o_status'  => array('in',array('-3','200','202','201','300','301','302','303')) ,
          'b.type' => array('in',array('sdp_order','sdp_refund'))
      );
      //$field = 'b.order_sn,a.item_id,b.create_time,a.price,a.item_code,d.amount,a.thumb,b.id,a.name,d.flow,d.type' ;
      $field = 'a.order_sn,a.item_ids,a.create_time,b.amount,a.id,b.flow,b.type' ;
      $order = array(
          'a.create_time' => 'desc',
          'b.create_time' => 'asc'
      );
      $lists = A('Page', 'Event')->lists($model, $where, $order, 6 ,'', $field);
      //查询当前登录用户的商户标识
      $secret = M('Shop')->where("uid='".UID."'")->getField("secret");
      foreach($lists as $key => $val){
          $item_id = explode(',',$val['item_ids']);
          $price = 0;
          $item_ids_arr = array();
          foreach($item_id as $k => $itd){
              //var_dump($val);
              $map['item_id'] = $itd;
              $map['sdp_code'] = $secret;
              $map['order_id'] = $val['id'];
              $result = M('OrderItem')->where($map)->field('id,item_id,price,item_code,thumb,name')->find();
              if($result){
                  $price += $result['price'];
                  $item_ids_arr[$k]['id'] = $result['id'];
                  $item_ids_arr[$k]['item_id'] = $result['item_id'];
                  $item_ids_arr[$k]['item_code'] = $result['item_code'];
                  $item_ids_arr[$k]['cover_path'] = get_cover($result['thumb'], 'path');
                  $item_ids_arr[$k]['name'] = $result['name'];
              }
          }
          $lists[$key]['price'] = $price;
          $lists[$key]['item_ids_arr'] = $item_ids_arr;
      }
      //var_dump($lists);
      //sql();
//      if($lists){
//          foreach($lists as $k => $v){
//              //不存在则为封面图片
//              $lists[$k]['cover_path'] =  get_cover($v['thumb'], 'path');
//          }
//      }
    if($lists){
      foreach($lists as $k => $v){
            //不存在则为封面图片
        $lists[$k]['cover_path'] =  get_cover($v['thumb'], 'path');
      }
    }
    $this->lists = $lists;
    $this->meta_title = '订单管理';
    $this->display(IS_AJAX ? 'orderList' : null);
  }

  /**
   * 店铺统计
   * @author Max.Yu <max@jipu.com>
   */
  public function stat($type = 'days'){
    if($type == 'days'){
      $stat_data = D('Shop')->getMonthData(); //获取月数据
    }else{
      $stat_data = D('Shop')->getYearData(); //获取年数据
    }
    $this->data = $stat_data;
    $this->type = $type;
    $this->meta_title = '店铺统计';
    $this->display();
  }
  
  /**
   * 开店引导
   * @author Max.Yu <max@jipu.com>
   */
  public function guide(){
    $shop = M('Shop')->getByUid(UID);
    if($shop){
      $this->redirect('Shops/add');
    }
    $this->meta_title = '分销店铺';
    $this->display();
  }
  
  /**
   * 提交开店申请
   * @author Max.Yu <max@jipu.com>
   */
  public function add(){
    $shop_secret = SHOP_SECRET;
    if(!empty($shop_secret)){
      $this->redirect('Member/sdp');
    }
    if(IS_POST){
      if(D('Shop')->update() !== false){
        $this->success('提交成功，等待审核！');
      }else{
        $this->error(D('Shop')->getError());
      }
    }else{
      
      $shop = M('Shop')->getByUid(UID);
      $this->audit_data = unserialize($shop['audit_data']);
      $this->shop = $shop;
      $this->meta_title = '提交申请信息';
      $this->display();
    }
  }

}
